<!--
 * @Author: thats-all-right-ha-ha 8280209+thats-all-right-ha-ha@user.noreply.gitee.com
 * @Date: 2024-06-17 17:16:44
 * @LastEditors: thats-all-right-ha-ha 8280209+thats-all-right-ha-ha@user.noreply.gitee.com
 * @LastEditTime: 2024-06-21 08:45:01
 * @FilePath: \cq-admin-vue3\src\views\wareHousing\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup>
import { getData, searchData, getDataByCateId, delData, outShop } from '@/api/wareHousing'
import useUserStore from '@/stores/modules/user'
import { getCategory } from '@/api/category'
import { getTableList } from '@/utils/Data'
import { ElMessage } from 'element-plus'
import { ref, onMounted } from 'vue'
const userStore = useUserStore()
defineOptions({ name: 'BannerIndex' })
//定义数据存放数组
const tableData = ref(0)
//分页
const pag = ref({
  page: 1,
  pageSize: 10,
  pagetotal: 10
})
//定义类别筛选数组
const iniCategory = async () => {
  const { page, pageSize } = pag.value
  const res = await getCategory({ page, pageSize })
  CATEGORY.value = res.data.dataAll.map((item) => {
    return {
      text: item.category,
      value: item.id
    }
  })
  console.log(res)
}
iniCategory()
const CATEGORY = ref([])
//定义弹窗打开状态值
const isShow = ref(false)
//获取数据
const getList = () => {
  getTableList(getData, pag, tableData)
}
getList()
//清空弹窗内容
const clear = () => {
  isShow.value = false
  out.value = ref({ id: null, number: null, place: null, username: userStore.username })
  maxNumber.value = null
}
//数字范围
const maxNumber = ref(null)
//数字校验规则
const isNumber = (rule, value, callback) => {
  if (typeof value !== 'number' || isNaN(value)) {
    callback(new Error('请输入数字'))
  } else if (value < 1 || value > maxNumber.value) {
    console.log(11)
    callback(new Error(`数量范围为1-${maxNumber.value}`))
  } else {
    callback()
  }
}
//表单校验
const rule = ref({
  place: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  quantity: [
    { required: true, message: '请输入数字', trigger: 'blur' },
    {
      validator: isNumber,
      trigger: 'blur'
    }
  ]
})

//出库数据
const out = ref({ id: null, quantity: null, place: null, username: userStore.username })

//搜索逻辑
const searchDetail = ref(null)
const search = async (title) => {
  if (!searchDetail.value) {
    getList()
    return false
  }
  const res = await searchData(searchDetail.value)
  tableData.value = res.data
  searchDetail.value = null
}
//删除逻辑
const handleDelete = async (row) => {
  const res = await delData(row.id)
  if (res.code === 20000) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
  }
  getList()
}

//分类筛选
const firstFilter = ref(true)
const categorySearch = async (value, column) => {
  if (firstFilter.value) {
    firstFilter.value = false
    if (value !== undefined) {
      if (column.property === 'category') {
        const res = await getDataByCateId(value)
        tableData.value = res.data
      }
    } else {
      getList()
    }
  }
}
const handleFilterChange = (filters) => {
  firstFilter.value = true
  if (filters.category) {
    categorySearch(filters.category[0], { property: 'category' }) // 传递正确的 column 参数
  }
}

//提交功能
const ruleForm = ref(null)
const submit = async () => {
  ruleForm.value.validate(async (ok) => {
    if (ok) {
      const res = await outShop(out.value)
      ElMessage({
        type: 'success',
        message: '出库成功'
      })
      clear()
      getList()
    } else {
      ElMessage({
        type: 'error',
        message: '请按要求填写'
      })
    }
  })
}

// 省市选择逻辑
const provinces = ref([])
const cities = ref([])
const selectedProvince = ref('')
const selectedCity = ref('')

// 获取省市数据
const fetchProvinces = async () => {
  try {
    const response = await fetch('/json/China.json') // 使用根路径
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data = await response.json()
    provinces.value = data.provinces
    allCities.value = data.cities
  } catch (error) {
    console.error('Error fetching the provinces:', error)
  }
}
const allCities = ref({})

// 处理省份变化
const handleProvinceChange = (value) => {
  selectedCity.value = ''
  cities.value = allCities.value[value] || []
  updatePlace()
}

// 更新 place 字段
const updatePlace = () => {
  out.value.place = `${selectedProvince.value}${selectedCity.value ? ' ' + selectedCity.value : ''}`
}

onMounted(() => {
  fetchProvinces()
})
</script>

<template>
  <div class="search">
    <el-input placeholder="搜索框" style="width: 240px" v-model="searchDetail"></el-input>
    <el-button @click="search">搜索</el-button>
  </div>
  <el-table style="width: 100%" :data="tableData" @filter-change="handleFilterChange">
    <el-table-column prop="id" label="ID" width="90" />
    <el-table-column prop="title" label="货品名" width="180" />
    <el-table-column prop="username" label="操作员名称" width="180" />
    <el-table-column prop="image" label="图片" width="180">
      <template #default="{ row }">
        <img :src="row.image" alt="" width="100px" />
      </template>
    </el-table-column>
    <el-table-column prop="quantity" label="数量" width="100" />
    <el-table-column
      prop="category"
      label="分类"
      width="90"
      column-key="category"
      :filters="CATEGORY"
      :filter-method="categorySearch"
      :filter-multiple="false"
    />
    <el-table-column prop="updateTime" label="添加时间" width="180" />
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button
          size="small"
          type="success"
          @click="(isShow = true), (maxNumber = row.quantity), (out.id = row.id)"
          :disabled="row.quantity === 0"
        >
          出库
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(row)"> 删除 </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="isShow" title="出库信息" :before-close="clear">
    <el-form label-width="auto" :model="out" :rules="rule" ref="ruleForm">
      <el-form-item label="出库数量" prop="quantity">
        <el-input v-model.number="out.quantity"></el-input>
      </el-form-item>
      <el-form-item label="发货地" prop="place">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-select
              v-model="selectedProvince"
              placeholder="请选择省份"
              @change="handleProvinceChange"
              style="width: 200px"
            >
              <el-option
                v-for="province in provinces"
                :key="province.value"
                :label="province.label"
                :value="province.value"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-select
              v-model="selectedCity"
              placeholder="请选择市"
              @change="updatePlace"
              style="width: 200px"
            >
              <el-option
                v-for="city in cities"
                :key="city.value"
                :label="city.label"
                :value="city.value"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <div class="dialog-footer">
        <el-button @click="clear">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <el-pagination
    background
    layout="prev, pager, next"
    :total="pag.pagetotal"
    v-model:page-size="pag.pageSize"
    v-model:current-page="pag.page"
    @change="getList"
  />
</template>

<style lang="scss" scoped>
.el-form-item {
  width: 400px;
}

.w600 {
  width: 600px;
}
</style>
